package com.example.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class GameManagement {
	
	private static GameManagement instance = null;
	
	private static Map<String, Player> players;
	private static ArrayList<String> turns;
	private static Player currentPlayer;
	private static int turn = 0;
	private static boolean gameOver;
	private static Player winner;
	private static String lastShot;
	private static ArrayList <SessionManagement> sessions;
	
	private GameManagement(){
		sessions = new ArrayList<SessionManagement>();
		players = new HashMap<String, Player>();
		turns = new ArrayList<String>();
		currentPlayer = new Player();
		winner = null;
		gameOver = false;
		lastShot = "";
	}
	
	public static synchronized GameManagement getInstance(){
		if(instance == null)
			instance = new GameManagement();
		return instance;
	}
	
	public static synchronized String addPlayer(){
		SessionManagement session;
		if(sessions.size() < 1){
			session = new SessionManagement();
			sessions.add(session);
		}
		else{
			if(sessions.get(sessions.size() - 1).getPlayers().size() >= 2){
				session = new SessionManagement();
				sessions.add(session);
			}
			else{
				session = sessions.get(sessions.size() - 1);
			}
		}
		Player player = new Player();
		player.setId("Player" + (session.getPlayers().size() + 1));
		session.addPlayer(player);
		return (sessions.size() + "|" + player.getId());
	}
	
	public static synchronized Map<String, Player> getPlayers(String session){
		return sessions.get(Integer.parseInt(session) - 1).getPlayers();
	}
	
	public static synchronized Player getCurrentPlayer(String session){
		return sessions.get(Integer.parseInt(session) - 1).getCurrentPlayer();
	}
	
	public static synchronized void nextTurn(String session){
		sessions.get(Integer.parseInt(session) - 1).nextTurn();
	}
	
	public static synchronized boolean isGameOver(String session){
		return sessions.get(Integer.parseInt(session) - 1).isGameOver();
	}
	
	public static synchronized void setGameOver(String session){
		sessions.get(Integer.parseInt(session) - 1).setGameOver(true);
	}
	
	public static synchronized Player getWinner(String session){
		return sessions.get(Integer.parseInt(session) - 1).getWinner();
	}
	
	public static synchronized void setWinner(String session, String player){
		if(sessions.get(Integer.parseInt(session) - 1).getWinner() == null)
			sessions.get(Integer.parseInt(session) - 1).setWinner(player);
	}

	public static synchronized String getLastShot() {
		return lastShot;
	}

	public static synchronized void setLastShot(String session, String lastShot) {
		sessions.get(Integer.parseInt(session) - 1).setLastShot(lastShot);
	}
	
}
